package org.lhq.goldenplugin.toolWindows

import com.intellij.openapi.components.service
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.project.Project
import com.intellij.openapi.wm.ToolWindow
import com.intellij.openapi.wm.ToolWindowFactory
import com.intellij.ui.content.ContentFactory
import com.intellij.ui.table.JBTable
import com.intellij.util.concurrency.AppExecutorUtil
import org.lhq.goldenplugin.i18n.GoldenBundle
import org.lhq.goldenplugin.service.PriceService
import org.lhq.goldenplugin.utils.DateUtils
import java.awt.BorderLayout
import java.awt.FlowLayout
import java.util.concurrent.TimeUnit
import javax.swing.*
import javax.swing.table.DefaultTableModel

class GoldenWindowsFactory : ToolWindowFactory {
    private val logger = logger<GoldenWindowsFactory>()

    override fun createToolWindowContent(
        project: Project,
        toolWindow: ToolWindow
    ) {
        val goldenToolWindow = GoldenWindows(toolWindow)
        val content = ContentFactory.getInstance().createContent(
            goldenToolWindow.getContent(),
            null,
            false
        )
        toolWindow.title = "GoldenPlugin"
        toolWindow.contentManager.addContent(content)
    }

    override fun shouldBeAvailable(project: Project): Boolean {
        return true
    }

    class GoldenWindows(toolWindow: ToolWindow) {
        private val executor = AppExecutorUtil.getAppScheduledExecutorService()
        private val loggerGoldenWindows = logger<GoldenWindows>()
        private val priceService = toolWindow.project.service<PriceService>()
        private var refreshButton: JButton? = null
        private var mainPanel: JPanel? = null
        private var table: JBTable? = null
        private var updateLabel: JLabel? = null
        private var thresholdField: JTextField? = null

        fun getContent(): JPanel? {
            val buttonJPanel = JPanel()
            buttonJPanel.layout = BoxLayout(buttonJPanel, BoxLayout.X_AXIS)
            val refreshButtonText = GoldenBundle.message("button.refresh")
            val updateTimeLabel = GoldenBundle.message("label.update.time")
            refreshButton = JButton(refreshButtonText)
            updateLabel = JLabel(updateTimeLabel + DateUtils.getCurrentTime())
            
            // 添加阈值设置组件
            val thresholdLabel = JLabel("阈值:")
            thresholdField = JTextField(priceService.goldPriceThreshold.takeIf { it > 0 }?.toString() ?: "", 10)
            val setThresholdButton = JButton("设置阈值")
            val resetNotificationButton = JButton("重置提醒")
            
            buttonJPanel.add(refreshButton)
            buttonJPanel.add(updateLabel)
            buttonJPanel.add(Box.createHorizontalStrut(20))
            buttonJPanel.add(thresholdLabel)
            buttonJPanel.add(thresholdField)
            buttonJPanel.add(setThresholdButton)
            buttonJPanel.add(resetNotificationButton)
            
            val data = getPrice()
            val tableModel = DefaultTableModel(data, arrayOf("名称", "买入价", "最高价", "最低价"))
            table = JBTable(tableModel)
            mainPanel = JPanel(BorderLayout())
            
            mainPanel?.add(buttonJPanel, BorderLayout.NORTH)
            mainPanel?.add(JScrollPane(table), BorderLayout.CENTER)
            
            refreshButton?.addActionListener { 
                refreshData()
                updateLabel?.text = updateTimeLabel + DateUtils.getCurrentTime()
            }
            
            setThresholdButton.addActionListener {
                try {
                    val inputText = thresholdField?.text?.trim()
                    if (inputText.isNullOrEmpty()) {
                        priceService.goldPriceThreshold = 0.0
                        JOptionPane.showMessageDialog(
                            mainPanel, 
                            "已清除阈值设置，提醒功能已关闭", 
                            "设置成功", 
                            JOptionPane.INFORMATION_MESSAGE
                        )
                        return@addActionListener
                    }
                    
                    val threshold = inputText.toDoubleOrNull()
                    if (threshold != null && threshold > 0) {
                        priceService.goldPriceThreshold = threshold
                        priceService.resetNotification() // 重置通知状态
                        
                        JOptionPane.showMessageDialog(
                            mainPanel, 
                            "阈值已设置为: $threshold\n当黄金价格达到或超过此值时将会提醒", 
                            "设置成功", 
                            JOptionPane.INFORMATION_MESSAGE
                        )
                    } else {
                        JOptionPane.showMessageDialog(
                            mainPanel, 
                            "请输入大于0的有效数值，或留空以关闭提醒功能", 
                            "输入错误", 
                            JOptionPane.ERROR_MESSAGE
                        )
                    }
                } catch (e: NumberFormatException) {
                    JOptionPane.showMessageDialog(
                        mainPanel, 
                        "请输入有效的数值", 
                        "输入错误", 
                        JOptionPane.ERROR_MESSAGE
                    )
                }
            }
            
            resetNotificationButton.addActionListener {
                priceService.resetNotification()
                JOptionPane.showMessageDialog(
                    mainPanel, 
                    "提醒状态已重置\n上次通知价格: ${priceService.getLastNotifiedPrice()}\n当前阈值: ${priceService.goldPriceThreshold}", 
                    "重置成功", 
                    JOptionPane.INFORMATION_MESSAGE
                )
            }
            
            executor.scheduleWithFixedDelay({
                refreshData()
                updateLabel?.text = "更新时间:" + DateUtils.getCurrentTime()
                loggerGoldenWindows.info("黄金数据更新 ${DateUtils.getCurrentTime()}")
            }, 10, 10, TimeUnit.SECONDS)
            
            return mainPanel
        }

        fun refreshData() {
            val data = getPrice()
            val tableModel = DefaultTableModel(data, arrayOf("名称", "买入价", "最高价", "最低价"))
            table?.model = tableModel
        }

        fun getPrice(): Array<Array<Any>> {
            val price = priceService.fetchPrice()
            val resultData = mutableListOf<Array<Any>>()
            price?.data?.sh?.forEach {
                resultData.add(arrayOf(it.name, it.bp, it.high, it.low))
            }
            price?.data?.gj?.forEach {
                resultData.add(arrayOf(it.name, it.bp, it.high, it.low))
            }
            price?.data?.lf?.forEach {
                resultData.add(arrayOf(it.name, it.bp, it.high, it.low))
            }
            return resultData.toTypedArray()
        }
    }
}